package com.gf.controller.mnue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gf.bean.Menu;
import com.gf.bean.MenuInfo;
import com.gf.service.impl.MenuServiceImpl;
import com.gf.utils.Const;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/*
 * 当点击购物车按钮的时候展示购物车里所有菜品的servlet
 * */

@WebServlet(name = "selectcart",urlPatterns = "/selectcart")
public class SelectcartServlet extends HttpServlet {
    static MenuServiceImpl menuimpl = null;

    static {
        menuimpl = new MenuServiceImpl();


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        //因为购物车会不断访问所以不能缓存以上三行代码就是不能设置缓存每次访问都会处理一遍
        PrintWriter out = response.getWriter();
        JSONObject backjson = new JSONObject();
        //新建json对象
        HttpSession session = request.getSession();
        //取出当前会话的session对象
        HashMap<String, Integer> shoppingcart = (HashMap<String, Integer>) session.getAttribute("shoppingcart");
        //再通过键取出购物车对象
        if (shoppingcart != null) {
            //当购物车不为空进入以下代码
            if (shoppingcart.size() == 0) {
                //当购物车的长度为0返回没有选任何菜品的提示
                session.setAttribute("shoppingcart", new HashMap<String, Integer>());
                response.setStatus(300);
                backjson.put("status", 300);
                backjson.put("message", Const.NODISH);
                out.println(JSON.toJSON(backjson));
                //输出字符串化的json字符串
            }else {
                //获取所有键用于下面的遍历
                Set<String> dishid = shoppingcart.keySet();
                Iterator<String> it = dishid.iterator();
                //创建dishid的set迭代对象
                ArrayList<Integer> dishs = new ArrayList<Integer>();
                //创建好list形式的数据结构用来下面的查询数据
                while (it.hasNext()) {
                    //单纯地从set集合中转移内容至list集合中
                    String next = it.next();
                    dishs.add(Integer.valueOf(next));

                }
                List<Menu> cartmenus = menuimpl.selectmenubydishid(dishs);
                //通过所有的dishid来查询出对应的菜品集合
                ArrayList<MenuInfo> menuInfos = new ArrayList<>();
                //创建出最终要返回的menuinfo类型的集合
                for (Menu cartmenu : cartmenus) { ;
                    //遍历通过dishid集合查询到的所有菜品集合
                    menuInfos.add(new MenuInfo(cartmenu, shoppingcart.get(String.valueOf(cartmenu.getDish_id()))));
                    //menuinfo里面包含着菜品对象和其对应的数量
                    //menuinfo里面的menu对象是直接通过遍历赋值的，而数量是通过菜品的dishid从购物车匹配对应的键对应的值取到的
                }
                int sum = 0;
                //这里就是稍微计算一下总价格而已
                for (MenuInfo menuInfo : menuInfos) {
                    //遍历刚才组装好饿menuinfos里面的menu对象每次取其值和menuinfo里面的num的数量相乘再累加
                    sum += menuInfo.getNum() * (menuInfo.getMenu().getPrice());
                }
                //全部完成后将要展示的menuinfos（包含着菜品和对应的数量）及其sum总价格以及返回成功的状态码
                response.setStatus(200);
                backjson.put("status", 200);
                backjson.put("data", menuInfos);
                backjson.put("sum", sum);

                out.println(JSON.toJSON(backjson));
                //将json对象转化为字符串后并输出
            }

    }else {
            //如果购物车对象是null就输出错误的响应码和对应的信息并且重新创建购物车对象
        session.setAttribute("shoppingcart", new HashMap<String, Integer>());

        response.setStatus(300);
        backjson.put("status", 300);
        backjson.put("menuinfos", "您还没有选任何菜品");
        out.println(JSON.toJSON(backjson));
//        打印输出
    }
                out.flush();
                out.close();


}


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
